from datetime import datetime
from app import db

class Meal(db.Model):
    __tablename__ = 'meals'

    meal_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    recipe_id = db.Column(db.Integer, db.ForeignKey('recipes.recipe_id'), nullable=False)
    header = db.Column(db.String(255), nullable=False)
    status = db.Column(db.Integer, nullable=False, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, onupdate=datetime.utcnow)
    calories = db.Column(db.Float)  # 每餐热量
    carbohydrate = db.Column(db.Float)  # 每餐碳水克数
    protein = db.Column(db.Float)  # 每餐蛋白质克数
    fat = db.Column(db.Float)  # 每餐脂肪克数
    # 关联
    recipe = db.relationship('Recipe', backref=db.backref('meals', lazy=True))

    # to_dict 方法
    def to_dict(self):
        return {
            'meal_id': self.meal_id,
            'header': self.header,
            'status': self.status,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
            'food_list': [meal_food.to_dict() for meal_food in self.meal_foods]  # 转换 meal_foods
        }
